<?php
import( 'classes.core.View' );
import( 'classes.view.panel.EnvironmentSelector' );
import( 'classes.model.Topic' );
import( 'classes.model.Case' );
import( 'classes.logic.Topic' );
import( 'classes.logic.Result' );
/**
 *	Option Views.
 *	@extends		Core_View
 *	@uses			View_Panel_PlatformSelector
 *	@author			Christian WÃ¼rker <Christian.Wuerker@CeuS-Media.de>
 *	@since			06.08.2007
 *	@version		0.1
 */
/**
 *	Option Views.
 *	@extends		Core_View
 *	@uses			View_Panel_PlatformSelector
 *	@author			Christian WÃ¼rker <Christian.Wuerker@CeuS-Media.de>
 *	@since			06.08.2007
 *	@version		0.1
 */
class View_Testing_Result extends Core_View
{
	private $nodeId;

	function __construct()
	{
		parent::__construct( true );
	}

	/**
	 *	Builds Car Views.
	 *	@access		public
	 *	@return		string
	 */
	public function buildContent()
	{
		$request	= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$session	= Framework_Krypton_Core_Registry::getStatic( 'session' );

		$selector	= new View_Panel_EnvironmentSelector();
		$selector->setServerProjects();

		$serverProjectId	= $session->get( 'serverProjectId' );
		if( $serverProjectId )
		{
			$selector->setRuns();
			$serverProjectData	= Logic_ServerProject::getServerProjectData( $serverProjectId );
			$projectId			= $serverProjectData['project_id'];
			$topicId			= $request->get( 'topicId' );
			$runId				= $session->get( 'runId' );
			$caseId				= $request->get( 'caseId' );
			if( $projectId && $runId )
			{
				$ui['tree']		= $this->buildContentTopicTree( $runId, $serverProjectId, $projectId, $topicId );
				if( $caseId )
				{
					$ui['content']	= $this->buildContentCaseView( $runId, $serverProjectId, $projectId, $topicId, $caseId );
					$ui['content']	.= $this->buildContentRecordList( $runId, $serverProjectId, $projectId, $topicId, $caseId );
					$ui['content']	.= $this->buildContentRecordAdd( $runId, $serverProjectId, $projectId, $topicId, $caseId );
				}
				else if( $topicId )
				{
					$ui['content']	= $this->buildContentTopicView( $projectId, $topicId );
					$ui['content']	.= $this->buildContentTopicCaseList( $projectId, $topicId );
				}
				else
				{
					$ui['content']	= $this->buildContentTopicCaseList( $projectId );
				}
			}
		}
		$ui['selector'] = $selector->buildContent();
		return $this->loadTemplate( 'testing.result.content', $ui );
	}

	private function buildContentRecordAdd( $runId, $serverProjectId, $projectId, $topicId, $caseId )
	{
		$request	= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$session	= Framework_Krypton_Core_Registry::getStatic( 'session' );
		$words		= $this->words['result']['addRecord'];

		$opt_status	= $this->words['result']['states'];
		$result	= Logic_Result::findResultByIds( $caseId, $runId );
		if( $result )
			$opt_status['_selected']	= $result['status'];

		$sources	= array(
			'opt_status'	=> $opt_status,
		);

		//  --  UI COMPONENTS  --  //
		$ui	= $this->buildForm( 'testing/result', 'addRecord', 'result', 'addRecord', array(), $sources );
		$button_cancel	= UI_HTML_Elements::LinkButton( "?link=".$request->get( 'link' )."&topicId=".$topicId, $words['button_cancel'] );
		$button_edit	= UI_HTML_Elements::Button( 'addRecord', $words['button_edit'] );
		$ui['field_button_cancel']	= UI_HTML_Elements::Field( '', $button_cancel );
		$ui['field_button_edit']	= UI_HTML_Elements::Field( '', $button_edit );

		$ui['form']		= UI_HTML_Elements::Form( 'addRecord', "?link=".$request->get( 'link' )."&topicId=".$topicId."&caseId=".$caseId, false, 'multipart/form-data' );
		$ui['caption']	= UI_HTML_Elements::TableCaption( $words['caption'], 'edit' );
		$ui['colgroup']	= UI_HTML_Elements::ColumnGroup( $words['colgroup'] );
		return $this->loadTemplate( 'testing.result.record.add', $ui );
	}

	private function buildContentRecordList( $runId, $serverProjectId, $projectId, $topicId, $caseId )
	{
		$config		= Framework_Krypton_Core_Registry::getStatic( 'config' );
		$words		= $this->words['result']['listRecords'];

		$resultData	= Logic_Result::findResultByIds( $caseId, $runId );
		if( $resultData )
		{
			$list		= array();
			$records	= Logic_Record::getRecordList( $resultData['result_id'], array(), array( 'timestamp' => "ASC" ) );
			foreach( $records as $record )
			{
				print_m( $record );
				if( $record['attachment_id'] )
				{
					$attachementData	= Logic_Attachment::getAttachmentData( $record['attachment_id'] );
					print_m( $attachementData );
					$attachment	= array(
						'path'			=> $config['paths']['attachments'],
						'uri'			=> $attachementData['uri'],
						'title'			=> nl2br( $this->cleanseString( $attachementData['title'] ) ),
						'description'	=> nl2br( $this->cleanseString( $attachementData['description'], KRYPTON_CLEANSE_SCRIPTS_AND_EVENTS ) ),
					);
					$record['attachment']	= $this->loadTemplate( 'testing.result.record.attachment', $attachment );
				}
				$record['tester']		= Logic_Authentication::getUsernameFromUid( $record['tester_id'] );
				$record['status_old']	= $this->words['result']['states'][$record['status_old']];
				$record['status_new']	= $this->words['result']['states'][$record['status_new']];
				$record['comment']		= $record['comment'] ? nl2br( $this->cleanseString( $record['comment'], KRYPTON_CLEANSE_SCRIPTS_AND_EVENTS ) ) : "";
				$list[]	= $this->loadTemplate( 'testing.result.record.item', $record );
			}
			$ui	= $words;
			$ui['list']	= implode( "\n", $list );
			$ui['caption']	= UI_HTML_Elements::TableCaption( $words['caption'], 'list' );
			$ui['colgroup']	= UI_HTML_Elements::ColumnGroup( $words['colgroup'] );
			return $this->loadTemplate( 'testing.result.record.list', $ui );
		}
	}

	private function buildContentCaseView( $runId, $serverProjectId, $projectId, $topicId, $caseId )
	{
		$request	= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$session	= Framework_Krypton_Core_Registry::getStatic( 'session' );
		$words		= $this->words['result']['viewCase'];

		$data	= Logic_Case::getCaseData( $caseId );
		$result	= Logic_Result::findResultByIds( $caseId, $runId );
		$data['status']			= $result ? $result['status'] : 0;
		$data['description']	= nl2br( $this->cleanseString( $data['description'], KRYPTON_CLEANSE_SCRIPTS_AND_EVENTS ) );
		$data['precondition']	= nl2br( $this->cleanseString( $data['precondition'], KRYPTON_CLEANSE_SCRIPTS_AND_EVENTS ) );

		$caption	= $words['caption'].' '.UI_HTML_Elements::Link( './?link=manageStructure&topicId='.$topicId."&caseId=".$caseId, 'ändern' );

		//  --  UI COMPONENTS  --  //
		$ui	= $this->buildForm( 'testing/result', 'viewCase', 'result', 'viewCase', $data );
		$ui['form']		= UI_HTML_Elements::Form( 'viewCase', "?link=".$request->get( 'link' )."&topicId=".$topicId."&caseId=".$caseId );
		$ui['caption']	= UI_HTML_Elements::TableCaption( $caption, 'edit' );
		$ui['colgroup']	= UI_HTML_Elements::ColumnGroup( $words['colgroup'] );
		return $this->loadTemplate( 'testing.result.case.view', $ui );
	}

	private function buildContentTopicView( $projectId, $topicId )
	{
		$request	= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$session	= Framework_Krypton_Core_Registry::getStatic( 'session' );
		$words		= $this->words['result']['viewTopic'];

		$data	= Logic_Topic::getTopicData( $topicId );
		$data['description']	= nl2br( $this->cleanseString( $data['description'], KRYPTON_CLEANSE_SCRIPTS_AND_EVENTS ) );

		$opt_parent	= array_merge( array( 0 => "" ), Logic_Topic::getTopicList( $projectId, 0, 0, "- " ) );
		$opt_parent['_selected']	= $data['parent_id'];
		$sources	= array( 'opt_parent' => $opt_parent );

		$caption	= $words['caption'].' '.UI_HTML_Elements::Link( './?link=manageStructure&topicId='.$topicId, 'ändern' );

		//  --  UI COMPONENTS  --  //
		$ui	= $this->buildForm( 'testing/result', 'viewTopic', 'result', 'viewTopic', $data );

		$ui['form']		= UI_HTML_Elements::Form( 'viewTopic', "?link=".$request->get( 'link' )."&topicId=".$topicId );
		$ui['caption']	= UI_HTML_Elements::TableCaption( $caption, 'view' );
		$ui['colgroup']	= UI_HTML_Elements::ColumnGroup( $words['colgroup'] );
		return $this->loadTemplate( 'testing.result.topic.view', $ui );
	}

	private function buildContentTopicCaseList( $projectId, $topicId = NULL )
	{
		$request	= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$session	= Framework_Krypton_Core_Registry::getStatic( 'session' );
		$words		= $this->words['result']['listCases'];
		$link	= $request->get( 'link' );
		$runId	= $session->get( 'runId' );

		$list	= array();
		$cases	= Logic_Case::getCaseList( $topicId );
		foreach( $cases as $case )
		{
			$resultData	= Logic_Result::findResultByIds( $case['case_id'], $runId );
			$case['modified']	= "-";
			if( $resultData )
			{
				$case['status']			= $resultData['status'];
				$case['statusLabel']	= $this->words['result']['states'][$resultData['status']];
				$case['testerLabel']	= Logic_Authentication::getUsernameFromUid( $resultData['tester_id'] );
				$case['modified']		= $resultData['timestamp'] ? date( "d.m.Y H:i", strtotime( $resultData['timestamp'] ) ) : "";
			}
			$case['author']		= Logic_Authentication::getUsernameFromUid( $case['author_id'] );
			$case['link']		= $link;
			$case['priorityLabel']		= $this->words['structure']['priorities'][$case['priority']];
			$case['created']	= $case['created'] ? date( "d.m.Y H:i", $case['created'] ) : "";
			$list[]	= $this->loadTemplate( 'testing.result.case.item', $case );
		}

		$ui	= $words;
		$ui['list']	= implode( "\n", $list );
		$ui['caption']	= UI_HTML_Elements::TableCaption( $words['caption'], 'view' );
		$ui['colgroup']	= UI_HTML_Elements::ColumnGroup( $words['colgroup'] );
		return $this->loadTemplate( 'testing.result.case.list', $ui );
	}

	private function buildContentTopicTree( $runId, $serverProjectId, $projectId, $topicId = 0 )
	{
		$config			= Framework_Krypton_Core_Registry::getStatic( 'config' );
		$request		= Framework_Krypton_Core_Registry::getStatic( 'request' );
		$words			= $this->words['result']['tree'];
		$currentLink	= $request->get( 'link' );
		$files			= array();

		$model	= new Model_Topic();
//		$st	= new Framework_Krypton_Core_StopWatch();
		//  --  CHECK CACHE  --  //
		$cached		= false;
		$cacheFile	= $config['paths']['cache']."testingTree_".$projectId.".cache";
		if( file_exists( $cacheFile ) )
		{
			$conditions	= array( 'project_id' => $projectId, 'modified' => ">=".filemtime( $cacheFile ) );
			$cached	= !(bool)$model->find( array( 'topic_id' ), $conditions );
		}
		if( $cached )
			$treeData	= unserialize( file_get_contents( $cacheFile ) );
		else
		{
			$treeData	= $this->constructTree( $runId, $serverProjectId, $projectId, $currentLink, 0, false, 0, array( 'id' => 'gray' ) );
			if( $treeData['tree'] )
				file_put_contents( $cacheFile, serialize( $treeData ) );
		}
//		remark( $st->stop() ) ;
		$ui['tree']		= $treeData['tree'];
		$heading		= $words['heading']." (".$treeData['topics']."|".$treeData['cases'].")";
		$ui['heading']	= UI_HTML_Elements::Link( "?link=".$currentLink, $heading );
		return $this->loadTemplate( 'management.structure.tree', $ui );
	}

	private function constructTree( $runId, $serverProjectId, $projectId, $currentLink, $parentId, $parentPath, $level, $attributes = array() )
	{
		$returnData	= array(
			'status'	=> 3,
			'cases'		=> 0,
			'topics'	=> 0,
			'tree'		=> "",
			);
		$list	= array();

		//  --  TEST CASES  --  //
		$model	= new Model_Case();
		$model->focusIndex( 'topic_id', $parentId );
		$cases	= $model->get( false );
		foreach( $cases as $case )
		{
			$returnData['cases'] ++;
			$path		= $parentPath . ( $parentPath ? ".".$case['case_id'] : $case['case_id'] );
			$attribs	= array( 'id' => 'li_'.$path );
			$result		= Logic_Result::findResultByIds( $case['case_id'], $runId );
			if( $result )
			{
				$attribs['class']	= "caseStatus".$result['status'];
				$returnData['status']	= min( $returnData['status'], $result['status'] );
			}
			else
				$returnData['status']	= 0;
			$link		= UI_HTML_Elements::Link( "?link=".$currentLink."&topicId=".$parentId."&caseId=".$case['case_id'], $case['title'], 'case' );
			$list[]		= UI_HTML_Elements::ListItem( $link, 0, $attribs );
		}

		//  --  TEST TOPICS  --  //
		$model	= new Model_Topic();
		$model->focusIndex( 'project_id', $projectId );
		$model->focusIndex( 'parent_id', $parentId );
		$nodes	= $model->get( false );
		foreach( $nodes as $node )
		{
			$path		= $parentPath . ( $parentPath ? ".".$node['topic_id'] : $node['topic_id'] );
			$subData	= $this->constructTree( $runId, $serverProjectId, $projectId, $currentLink, $node['topic_id'], $path, $level+1 );
			$returnData['status']	= min( $returnData['status'], $subData['status'] );
			$returnData['cases']	+= $subData['cases'];
			$returnData['topics']	+= $subData['topics'];
			$attribs	= array(
				'id'	=> 'li_'.$path,
				'class'	=> 'topicStatus'.$subData['status'],
			);
			$link		= UI_HTML_Elements::Link( "?link=".$currentLink."&topicId=".$node['topic_id'], $node['title'], 'topic' );
			$list[]		= UI_HTML_Elements::ListItem( $link.$subData['tree'], 0, $attribs );
		}
		$attributes['class']	= "tree_".$currentLink."_".$parentId;
		if( count( $list ) )
			$returnData['tree']	= UI_HTML_Elements::unorderedList( $list, $level, $attributes );
		return $returnData;
	}
}
?>
